package com.剑指offer;

import java.util.Arrays;

public class _4重建二叉树
{
    public TreeNode buildTree(int[] preorder, int[] inorder)
    {
        if (preorder.length == 0 || inorder.length == 0)
        {
            return null;
        }
        int rootVal = preorder[0];
        int rootIndex = 0;
        for (int i = 0; i < inorder.length; i++)
        {
            if (rootVal == inorder[i])
            {
                rootIndex = i;
                break;
            }
        }
        TreeNode rootNode = new TreeNode(rootVal);
        rootNode.left = buildTree(Arrays.copyOfRange(preorder, 1, rootIndex + 1), Arrays.copyOfRange(inorder, 0, rootIndex));
        rootNode.right = buildTree(Arrays.copyOfRange(preorder, rootIndex + 1, preorder.length), Arrays.copyOfRange(inorder, rootIndex + 1, inorder.length));
        return rootNode;
    }
}
